package com.damai.excel;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Collection;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.IndexedColors;
import org.apache.poi.ss.util.CellRangeAddress;

import com.citywithincity.utils.IoUtil;

public class ExcelTable {

	HSSFWorkbook hwb;
	// 这里进行创建excel
	HSSFSheet sheet;
	int cols = 0;
	int startIndex = 0;

	public ExcelTable() {

		FileOutputStream out = null;
		try {
			hwb = new HSSFWorkbook();

		} finally {
			IoUtil.close(out);
			if (hwb != null) {
				try {
					hwb.close();
				} catch (Exception e) {
				}
			}
		}
	}
	
	

	public ExcelTable createSheet(String name) {
		sheet = hwb.createSheet(name);
		startIndex = 0;
		return this;
	}
	
	public ExcelTable setSheet(int index){
		hwb.setActiveSheet(index);
		sheet = hwb.getSheetAt(index);
		return this;
	}

	public ExcelTable save(File file) throws IOException {

		FileOutputStream out = null;
		try {
			out = new FileOutputStream(file);
			hwb.write(out);
			return this;
		} finally {
			IoUtil.close(out);
		}
	}
	
	public void write(OutputStream outputStream) throws IOException{
		hwb.write(outputStream);
	}

	public void close() throws IOException {
		if (hwb != null)
			hwb.close();
	}

	public ExcelTable addRow(String[] cols) {
		this.cols = cols.length;
		HSSFRow row = sheet.createRow(startIndex++);
		int index = 0;
		for (String val : cols) {
			HSSFCell cell = row.createCell(index++);
			cell.setCellValue(val);
		}
		return this;
	}
	
	

	public int getIndex(){
		return startIndex;
	}

	public ExcelTable addRow(Collection<String> cols) {
		this.cols = cols.size();
		HSSFRow row = sheet.createRow(startIndex++);
		int i = 0;
		for (String val : cols) {
			HSSFCell cell = row.createCell(i);
			cell.setCellValue(val);
			++i;
		}
		return this;
	}

	//颜色
	
	public ExcelTable addRow(String value, int cols) {
		
		 CellStyle style = hwb.createCellStyle();
		 style.setFillForegroundColor(IndexedColors.GREY_25_PERCENT.getIndex());
		style.setFillPattern(CellStyle.SOLID_FOREGROUND);
		HSSFRow row = sheet.createRow(startIndex);
		HSSFCell cell = row.createCell(0);
		cell.setCellValue(value);
		cell.setCellStyle(style);
		
		CellRangeAddress cra = new CellRangeAddress(startIndex, startIndex, 0, cols);
		// 在sheet里增加合并单元格
		sheet.addMergedRegion(cra);
		++startIndex;
		return this;
	}

}
